package org.third.security.https;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.third.common.utils.CommonUtils;
import org.third.common.utils.StreamUtils;

public class HttpsClientTest {
    static SSLSocketFactory sf;

    static {
        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("TLS");
            System.out.println(KeyManagerFactory.getDefaultAlgorithm());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(new FileInputStream("C:/software/server/tomcat8030_8080/conf/tomcat_client.p12"), "tomcat1".toCharArray());
            kmf.init(ks, "tomcat1".toCharArray());
            
            TrustManager [] tm = new TrustManager[]{new X509TrustManager(){

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                
            }};
            sslContext.init(kmf.getKeyManagers(), tm, new java.security.SecureRandom());

            sf = sslContext.getSocketFactory();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        try {
            URL url = new java.net.URL("https://gongyo4.asiapacific.hpqcorp.net:8443/index.jsp");
            URLConnection conn = url.openConnection();
            HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
            httpsConn.setSSLSocketFactory(sf);

            InputStream in = httpsConn.getInputStream();
            String str = StreamUtils.streamToString(in, CommonUtils.UTF8_CHARSET);

            System.out.println(str);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
